package org.spring.aicloud.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**+
 * Spring Security 框架配置
 */
@Configuration
@EnableWebSecurity
public class SecuriryConfig {
    @Resource
    private LoginAuthenticationFilter loginAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .httpBasic(AbstractHttpConfigurer::disable) // 禁用明文验证
                .csrf(AbstractHttpConfigurer::disable) // 禁用 CSRF 验证
                .formLogin(AbstractHttpConfigurer::disable) // 禁用默认登录页
                .logout(AbstractHttpConfigurer::disable) // 禁用默认注销页
                .headers(AbstractHttpConfigurer::disable) // 禁用默认 Header（支持 iframe 访问页面）
                .sessionManagement(session -> // 禁用 Session（项目中是使用 JWT 认证）
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers( // 允许访问的资源
                                "/layui/**",
                                "/js/**",
                                "/css/**",
                                "/login.html",
                                "/index.html",
                                "/register.html",
                                "/user/login",
                                "/user/register",
                                "/captcha/create",
                                "/discuss/list",
                                "/kafka/**",
                                "/swagger-ui/**",
                                "/v3/**",
                                "/doc.html",
                                "/webjars/**",
                                "/user/login"

                        ).permitAll()
                        .anyRequest().authenticated() // 其他请求都需要认证
                )
                // 添加自定义登录认证过滤器
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
